import React, { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Textarea } from '@/components/ui/textarea'
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger
} from '@/components/ui/dialog'
import { createPiece, loadPieceProps } from '@/apis/piece'
import { Piece, PieceProps } from '@/types/piece'
import { toast } from '@/hooks/use-toast'
import { Switch } from '@/components/ui/switch'
import { ImageBedPicker } from '@/components/ui/image-picker'
import { usePieceStore } from '@/store/piece'

interface CreatePieceProps {
  type?: number // 1:装备 2:首饰
  onSuccess?: () => void
}

// 定义图床配置
const IMAGE_BEDS = [
  { id: '14097', name: '1' },
  { id: '14099', name: '2' },
  { id: '14100', name: '3' }
]

export default function CreatePiece({ type = 1, onSuccess }: CreatePieceProps) {
  const [open, setOpen] = useState(false)
  const [formData, setFormData] = useState<Omit<Piece, 'id'>>({
    name: '',
    avatar: '',
    group: '合成碎片',
    score: 7,
    props: '',
    alias: '',
    describe: '',
    status: 1,
    type
  })
  const [loading, setLoading] = useState(false)
  const [pieceProps, setPieceProps] = useState<PieceProps[]>([])
  const [selectedProps, setSelectedProps] = useState<number[]>([])
  const [propsLoading, setPropsLoading] = useState(false)
  const { addpiece } = usePieceStore()

  useEffect(() => {
    const fetchPieceProps = async () => {
      if (open && pieceProps.length === 0) {
        setPropsLoading(true)
        try {
          const props = await loadPieceProps()
          setPieceProps(props)
        } catch (error) {
          toast({
            title: '错误',
            description: '获取属性列表失败: ' + (error as Error).message,
            variant: 'destructive'
          })
        } finally {
          setPropsLoading(false)
        }
      }
    }

    fetchPieceProps()
  }, [open, pieceProps.length])

  const handleChange = (
    e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
  ) => {
    const { name, value } = e.target
    setFormData((prev) => ({
      ...prev,
      [name]: name === 'score' ? Number(value) : value
    }))
  }

  const handlePropToggle = (propId: number) => {
    setSelectedProps((prev) => {
      const newSelected = prev.includes(propId)
        ? prev.filter((id) => id !== propId)
        : [...prev, propId]

      // 更新表单中的props字段
      setFormData((formData) => ({
        ...formData,
        props: newSelected.join(',')
      }))

      return newSelected
    })
  }

  // 处理图床图片选择
  const handleImageSelect = (imageSliceId: string) => {
    setFormData((prev) => ({
      ...prev,
      avatar: imageSliceId
    }))
  }

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    setLoading(true)

    try {
      const dataToSubmit: Omit<Piece, 'id' | 'created_at' | 'updated_at'> = {
        ...formData
      }
      const result = await createPiece(dataToSubmit as Piece)

      if (result) {
        toast({
          title: '成功',
          description: '碎片创建成功'
        })
        // 添加新创建的碎片到store中
        addpiece(result)
        setOpen(false)
        setFormData({
          name: '',
          avatar: '',
          group: '',
          score: 0,
          props: '',
          alias: '',
          describe: '',
          status: 1,
          type
        })
        setSelectedProps([])
        onSuccess?.()
      } else {
        toast({
          title: '错误',
          description: '创建碎片失败',
          variant: 'destructive'
        })
      }
    } catch (error) {
      toast({
        title: '错误',
        description: '创建碎片时发生错误: ' + (error as Error).message,
        variant: 'destructive'
      })
    } finally {
      setLoading(false)
    }
  }

  return (
    <Dialog
      open={open}
      onOpenChange={(isOpen) => {
        setOpen(isOpen)
        if (!isOpen) {
          // 关闭对话框时重置选中状态
          setSelectedProps([])
        }
      }}
    >
      <DialogTrigger asChild>
        <Button
          variant="ghost"
          size="sm"
          className="h-6 rounded border-none px-1 text-[10px] text-gray-800 shadow-none hover:text-gray-900"
        >
          创建碎片
        </Button>
      </DialogTrigger>
      <DialogContent>
        <DialogHeader>
          <DialogTitle>创建新碎片</DialogTitle>
        </DialogHeader>
        <div>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div>
              <label htmlFor="name" className="mb-1 block text-sm font-medium">
                名称
              </label>
              <Input
                id="name"
                name="name"
                value={formData.name}
                onChange={handleChange}
                required
                placeholder="例如: 攻击力碎片"
              />
            </div>

            <div>
              <label htmlFor="alias" className="mb-1 block text-sm font-medium">
                简称
              </label>
              <Input
                id="alias"
                name="alias"
                value={formData.alias}
                onChange={handleChange}
                placeholder="例如: 攻击力"
              />
            </div>

            <div>
              <label
                htmlFor="avatar"
                className="mb-1 block text-sm font-medium"
              >
                碎片图
              </label>
              <div className="space-y-2">
                <div className="flex gap-2">
                  <Input
                    id="avatar"
                    name="avatar"
                    value={formData.avatar}
                    onChange={handleChange}
                    placeholder="请点击下方的图片选择"
                  />
                </div>

                <div className="flex flex-wrap gap-2">
                  {IMAGE_BEDS.map((bed) => (
                    <ImageBedPicker
                      key={bed.id}
                      imageBedId={bed.id}
                      onImageSelect={handleImageSelect}
                      title={`${bed.name}`}
                    />
                  ))}
                </div>

                {/* 移除单独的ImageBedPicker组件 */}
              </div>
            </div>

            <div>
              <label htmlFor="group" className="mb-1 block text-sm font-medium">
                归类
              </label>
              <Input
                id="group"
                name="group"
                value={formData.group}
                onChange={handleChange}
                placeholder="例如: 合成碎片"
              />
            </div>

            <div>
              <label htmlFor="score" className="mb-1 block text-sm font-medium">
                P数
              </label>
              <Input
                id="score"
                name="score"
                type="number"
                value={formData.score || ''}
                onChange={handleChange}
                placeholder="7p（默认）"
              />
            </div>

            <div>
              <label className="mb-1 text-sm font-medium">属性</label>
              {propsLoading ? (
                <div>加载属性中...</div>
              ) : (
                <div className="max-h-40 overflow-y-auto rounded border p-2">
                  {pieceProps.map((prop) => (
                    <div
                      key={prop.id}
                      className="flex items-center justify-between py-1"
                    >
                      <span className="text-sm">
                        {prop.title} ({prop.name})
                      </span>
                      <Switch
                        checked={selectedProps.includes(prop.id)}
                        onCheckedChange={() => handlePropToggle(prop.id)}
                      />
                    </div>
                  ))}
                  {pieceProps.length === 0 && <div>暂无属性可选</div>}
                </div>
              )}
              <Input
                id="props"
                name="props"
                value={formData.props}
                onChange={handleChange}
                placeholder="选中的属性ID将自动填充此处"
                className="mt-2"
                readOnly
              />
            </div>

            <div>
              <label
                htmlFor="describe"
                className="mb-1 block text-sm font-medium"
              >
                描述
              </label>
              <Textarea
                id="describe"
                name="describe"
                value={formData.describe}
                onChange={handleChange}
                rows={3}
                placeholder="请输入碎片描述信息"
              />
            </div>

            <div className="flex justify-end space-x-2">
              <Button
                type="button"
                variant="outline"
                onClick={() => setOpen(false)}
              >
                取消
              </Button>
              <Button type="submit" disabled={loading}>
                {loading ? '创建中...' : '创建'}
              </Button>
            </div>
          </form>
        </div>
      </DialogContent>
    </Dialog>
  )
}
